package com.cake.liulanxiangzhu.security;


import com.cake.liulanxiangzhu.mapper.AdminUserMapper;
import com.cake.liulanxiangzhu.pojo.vo.AdminUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private AdminUserMapper adminUserMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        log.debug("执行了用户和密码验证");
        AdminUserVO adminUserVO = adminUserMapper.selectPermission(userName);
        if (adminUserVO == null) {
            String message = "登录失败，用户名不存在！";
            throw new BadCredentialsException(message);
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission : adminUserVO.getPermissions()) {
            GrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }
        AdminDetails adminDetails = new AdminDetails(adminUserVO.getUsername(),adminUserVO.getPassword(),adminUserVO.getEnable()==1,authorities);
        adminDetails.setId(adminUserVO.getId());
        return adminDetails;
    }
}
